<template>
  <div class="page-mobile-discount">
    <div class="bg_box"></div>
    <div class="discount-content">
      <div :class="['header-top',scroll > 0 ?'active':'']">
        <div class="header_left" @click="$router.back()">
          <van-icon name="arrow-left" style="margin-left:.2rem;" />
        </div>
        <div class="center_title">折扣</div>
        <div class="header_right"></div>
      </div>
      <div class="fixed-box"></div>
      <div class="tap-content">
        <div
          :class="['tap', item.is_actived ? 'active' : null]"
          v-for="(item, index) in major_rec_list"
          :key="index"
          @click="handleClickTap(item)"
        >{{item.name}}</div>
      </div>
      <div class="discount-container">
        <div class="discount-hot">
          <div class="course-box" v-for="(item,index) in hotFourCourse" :key="index" @click="toPath(item.id)">
            <div class="course-img">
              <img :src="item.iconPath" alt />
            </div>
            <div class="course-name">{{item.courseName}}</div>
            <div class="price">
              <img src="/img/mobile/discount-price-one.png" alt />
              <div class="price-left">
                <div style="font-size: .3rem;">
                  <span style="font-size: .2rem;">&yen;</span>
                  {{item.discountPrice.toFixed(2)}}
                </div>
                <div class="old-price">&yen;{{item.price.toFixed(2)}}</div>
              </div>
              <div class="price-right">热卖中</div>
            </div>
          </div>
          <div class="right-position">&nbsp;</div>
        </div>
      </div>
      <div class="discount-list">
        <div class="list-item" v-for="(item,index) in remainList" :key="index" @click="toPath(item.id)">
          <div class="course-left">
            <img :src="item.iconPath" alt />
          </div>
          <div class="course-right">
            <div class="course-title">{{item.courseName}}</div>
            <div class="course-price">
              <img src="/img/mobile/discount-price-two.png" alt />
              <div class="price-left">
                <div style="font-size: .3rem;">
                  <span style="font-size: .2rem;">&yen;</span>
                  {{item.discountPrice.toFixed(2)}}
                </div>
                <div class="old-price">&yen;{{item.price.toFixed(2)}}</div>
              </div>
              <div class="price-right">已售{{item.studentSum}}件</div>
            </div>
          </div>
        </div>
        <div class="footer" v-show="remainList.length != 0">
          <span class="tips">我是有底线的</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import CourseCard from "~/components/mobile/CourseCard.vue";
import WhiteHeader from "~/components/mobile/WhiteHeader.vue";
import { getCourse, getCourseByMajor } from "~/api/course";
import { getMajorList } from "~/api/major";
import { getMemberInfo, getMember } from "~/api/member";
import { mapState, mapActions, mapMutations } from "vuex";
export default {
  props: ["setDisabled", "refreshFun", "setLoading"],
  components: {
    CourseCard,
    WhiteHeader,
  },
  data() {
    return {
      page: 1,
      pageSize: 10,
      total: 0,
      course_list: [],
      scroll_heigth: 0,
      memberDiscount: {},
      major_rec_list: [], //推荐专业
      action: "",
      title: "折扣",
      scroll: 0,
    };
  },
  computed: {
    ...mapState({
      token(state) {
        return state.token;
      },
      user_info(state) {
        return state.user_info;
      },
      major_list(state) {
        return [
          {
            text: this.$t("locale.mobile.course.t3"),
            value: "",
          },
          ...state.major_list.map((i) => {
            return {
              ...i,
              value: i.id,
              text: i.name,
            };
          }),
        ];
      },
      class_list(state) {
        return state.class_list;
      },
      is_loading(state) {
        return state.is_loading;
      },
      is_member(state) {
        return JSON.stringify(state.member_info) != "{}";
      },
      user_member(state) {
        return state.member_info;
      },
    }),
    hotFourCourse() {
      return this.course_list.filter((item, index) => index < 4);
    },
    remainList() {
      return this.course_list.filter((item, index) => index >= 4);
    },
  },
  watch: {},
  methods: {
    ...mapMutations(["SET_IS_LOADING"]),
    ...mapActions(["initMajorList", "initClassList", "initMember"]),
    toPath(id) {
      this.$router.push({
        path: "/m/course-detail",
        query: {
          id
        }
      });
    },
    async getMajorData() {
      this.SET_IS_LOADING(true);
      let params = {
        offset: 0,
        limit: 10,
        sort: "videoSort desc",
        isRec: 1,
      };
      let result = await getMajorList(params);
      if (result && result.data && result.data.code == 200) {
        this.SET_IS_LOADING(false);
        this.major_rec_list = [
          {
            name: this.$t("locale.mobile.index.t8"),
            id: "all",
            is_actived: true,
          },
          ...result.data.data.rows
            .filter((i) => i.isRec == 1)
            .map((i, x) => {
              return { ...i, is_actived: false };
            }),
        ];
      } else {
        this.SET_IS_LOADING(false);
        this.$toast(
          this.$t("locale.mobile.index.t9") + result &&
            result.data &&
            result.data.msg
        );
      }
    },
    async handleClickTap(item) {
      if (item.id == this.major_rec_list.filter((i) => i.is_actived)[0]) {
        return false;
      }
      this.major_rec_list = this.major_rec_list.map((i) => {
        if (i.id == item.id) {
          return {
            ...i,
            is_actived: true,
          };
        } else {
          return {
            ...i,
            is_actived: false,
          };
        }
      });
      this.page = 1;
      if (item.id == "all") {
        this.getData();
        // this.getData();
      } else {
        this.getData({
          majorId: item.id,
        });
        // this.getData({
        //   majorId: item.id
        // });
      }
    },
    async getMemberInfo() {
      this.SET_IS_LOADING(true);
      if (this.token && Object.keys(this.user_info).length > 0) {
        let result = await getMemberInfo(this.user_info.id);
        if (result && result.data && result.data.code == 200) {
          this.memberDiscount = result.data.data;
        } else {
          
        }
      }

      this.SET_IS_LOADING(false);
    },
    async getData(other_params, fetch_type) {
      return new Promise(async (resolve, reject) => {
        this.SET_IS_LOADING(true);
        let params = {
          offset: this.pageSize * (this.page - 1),
          limit: this.pageSize,
          // sort: "sortIndex desc",
          sort: 'sortIndex',
          sortType: 'desc',
          isDiscount: 1,
          ...other_params,
        };
        // let params = {
        //   offset: this.pageSize * (this.page - 1),
        //   limit: this.pageSize,
        //   sort: "sortIndex desc",
        //   isRec: 1,
        //   ...other_params,
        // };
        let result = await getCourse(params);
        if (result && result.data && result.data.code == 200) {
          this.SET_IS_LOADING(false);
          this.total = result.data.data.total;
          // if (fetch_type == "pullup") {
          //   this.course_list = [...this.course_list, ...result.data.data.rows];
          // } else {
          //   this.course_list = result.data.data.rows;
          // }
          // 加一层折扣时间的判断,不在折扣时间内判定为不是折扣课程
          let courseArr = [];
          if (fetch_type == "pullup") {
            courseArr = [...this.course_list,...result.data.data.rows];
          }else{
            courseArr = result.data.data.rows;
          }
          this.course_list = courseArr.map(item=>{
            let currentTime = new Date().getTime();
            if(!(item.isDiscount == 1 && currentTime >= item.discountStartTime && item.discountEndTime >= currentTime)){
              return {
                ...item,
                isDiscount:0
              };
            }else{
              return item;
            }
          }).filter(item=>item.isDiscount == 1);
        } else {
          this.SET_IS_LOADING(false);
          this.$toast(
            this.$t("locale.mobile.index.t9"),
            result && result.data && result.data.msg
          );
        }
      })
        .then()
        .catch((e) => {
          this.SET_IS_LOADING(false);
        });
    },
    getMajorName(id) {
      let res = this.major_list.filter((i) => i.id == id);
      if (res.length > 0) {
        return res[0].name;
      } else {
        return this.$t("locale.mobile.course.t4");
      }
    },
    initPage() {
      return new Promise((res, rej) => {
        if (process.client) {
          try {
            this.getData();
            this.getMajorData();
            this.getMemberInfo();
            this.initMember();
            res("success");
          } catch (e) {
            console.log(e);
            rej(e);
          }
        }
      }).then();
    },
    throttle(fn, delay) {
      let lastTime = 0;
      return !(function () {
        let nowTime = Date.now();
        if (nowTime - lastTime > delay) {
          fn.call(this);
          lastTime = nowTime;
        }
      })();
    },
    pullUp() {
      // 滚动条离顶部的距离
      let scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      // 窗口可视区域高度
      let clientHeight =
        document.documentElement.clientHeight || document.body.clientHeight;
      // 滚动区域高度
      let scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight;
      // 滚动条 + 可视区域高度 >= 滚动条高度 ==>  滚动条触底
      if (scrollTop + clientHeight >= scrollHeight - 120) {
        console.log("上拉加载");
        if (this.total <= this.course_list.length) {
          return;
        }
        if (this.is_loading) {
          return;
        }
        this.page++;
        this.getData({}, "pullup");
      }
    },
    eventListener() {
      this.scroll =
        document.documentElement.scrollTop || document.body.scrollTop;
      this.throttle(this.pullUp, 30);
    },
    initState() {
      this.page = 1;
      this.pageSize = 10;
      this.total = 0;
    },
  },
  activated() {
    if (process.client) {
      this.$nextTick(() => {
        setTimeout(() => {
          document.body.scrollTop = this.scroll_heigth;
          document.documentElement.scrollTop = this.scroll_heigth;
        }, 0);
      });
      window.addEventListener("scroll", this.eventListener);
      this.initPage();
    }
    this.setDisabled(false);
    this.refreshFun(() => {
      this.initPage()
        .then((res) => {
          if (res == "success") {
            this.setLoading(false);
          }
        })
        .catch(() => {
          this.setLoading(false);
          this.SET_IS_LOADING(false);
        });
    });
  },
  deactivated() {
    let scroll_heigth =
      document.documentElement.scrollTop || document.body.scrollTop;
    this.scroll_heigth = scroll_heigth;
    this.initState();
    this.setDisabled(true);
    window.removeEventListener("scroll", this.eventListener);
  },
  beforeDestroy() {
    window.removeEventListener("scroll", this.eventListener);
  },
  created() {
    //开启下拉刷新
    this.setDisabled(false);
    //初始化页面数据
    this.initPage();
    //下拉回调
    this.refreshFun(() => {
      this.initPage()
        .then((res) => {
          if (res == "success") {
            this.setLoading(false);
          }
        })
        .catch(() => {
          this.setLoading(false);
          this.SET_IS_LOADING(false);
        });
    });
    //返回上次页面滚动条的位置
    // this.$nextTick(() => {
    //   document.body.scrollTop = this.scroll_heigth;
    //   document.documentElement.scrollTop = this.scroll_heigth;
    // });
  },
  mounted() {
    if (process.client) {
      window.addEventListener("scroll", this.eventListener);
    }
  },
};
</script>

<style lang="scss" scoped>
.page-mobile-discount {
  // min-height: calc(100vh - 1.6rem);
  min-height: 100vh;
  .bg_box {
    position: fixed;
    left: 0;
    top: 0;
    width: 100vw;
    height: 100vh;
    // background: chartreuse;
    z-index: 0;
    background-image: url("/img/mobile/discount-bg.png");
    background-repeat: no-repeat;
    background-size: 100% 100%;
  }
  .discount-content {
    .discount-container {
      position: relative;
      z-index: 1;
      margin-top: .5rem;
      .discount-hot {
        // width: 6.9rem;
        // margin-top: 0.3rem;
        width: 7.2rem;
        overflow-x: scroll;
        overflow-y: hidden;
        -webkit-backface-visibility: hidden;
        -webkit-perspective: 1000;
        -webkit-overflow-scrolling: touch;
        text-align: justify;
        box-sizing: border-box;
        display: flex;
        &::-webkit-scrollbar {
          display: none;
        }
        .course-box {
          flex-shrink: 0;
          width: 3.456rem;
          height: 3.84rem;
          background: #ffffff;
          margin: 0 .3rem;
          border-radius: .1rem;
          position: relative;
          .course-img{
            width: 100%;
            height: 2.304rem;
            overflow: hidden;
            // border-radius: .1rem;
            border-top-left-radius: .1rem;
            border-top-right-radius: .1rem;
            background: var(--theme-color);
            img{
              width: 100%;
              height: 100%;
              display: block;
            }
          }
          .course-name{
            padding: .1rem .1rem 0 .1rem;
            font-size: .3rem;
            line-height: .36rem;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            // display: -webkit-box;
            // -webkit-line-clamp: 2;
            // -webkit-box-orient: vertical;
          }
          .price{
            width: 2.88rem;
            height: .86rem;
            position: absolute;
            right: -0.154rem;
            bottom: .02rem;
            img{
              width: 100%;
              height: 100%;
              display: block;
            }
            .price-left{
              position: absolute;
              font-size: .2rem;
              line-height: .26rem;
              padding: .2rem 0;
              text-align: center;
              color: #ffffff;
              width: 1.8rem;
              left: 0;
              top: 0;
              .old-price{
                text-decoration: line-through;
              }
            }
            .price-right{
              position: absolute;
              font-size: .26rem;
              line-height: .86rem;
              height: .86rem;
              // padding: .1rem 0;
              text-align: center;
              color: #ffffff;
              right: 0;
              top: 0;
              width: 1.056rem;
            }
          }
        }
        .right-position{
          transform: scale(0.1);
        }
      }
    }
    .discount-list{
      position: relative;
      z-index: 1;
      margin-top: .5rem;
      .list-item{
        width: 6.624rem;
        height: 2.3424rem;
        border-radius: .2rem;
        background: #ffffff;
        margin: 0 auto;
        box-sizing: border-box;
        padding: 0 .288rem;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .course-left{
          width: 2.592rem;
          height: 1.728rem;
          background: var(--theme-color);
          overflow: hidden;
          border-radius: .1rem;
          img{
            display: block;
            width: 100%;
            height: 100%;
          }
        }
        .course-right{
          width: 3.2rem;
          height: 1.728rem;
          position: relative;
          // background: var(--theme-color);
          .course-title{
            font-size: .3rem;
            line-height: .36rem;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
          }
          .course-price{
            width: 3.312rem;
            height: .691rem;
            position: absolute;
            right: -.288rem;
            bottom: 0rem;
            img{
              width: 100%;
              height: 100%;
              display: block;
            }
            .price-left{
              position: absolute;
              font-size: .2rem;
              line-height: .26rem;
              padding: .1rem 0;
              text-align: center;
              color: #ffffff;
              width: 1.824rem;
              left: 0;
              top: 0;
              .old-price{
                text-decoration: line-through;
              }
            }
            .price-right{
              position: absolute;
              font-size: .2112rem;
              line-height: .691rem;
              height: .691rem;
              // padding: .1rem 0;
              text-align: center;
              color: #ffffff;
              right: 0;
              top: 0;
              width: 1.488rem;
            }
          
          }
        }
      }
      .footer {
      padding: 0.3rem;
      font-size: 0.26rem;
      color: #ffffff;
      text-align: center;
      .tips {
        position: relative;
      }
      .tips::before {
        content: "";
        display: block;
        position: absolute;
        left: -1.7rem;
        top: 50%;
        transform: translateY(-1px);
        width: 1.5rem;
        height: 1px;
        background: #ffffff;
      }
      .tips::after {
        content: "";
        display: block;
        position: absolute;
        right: -1.7rem;
        top: 50%;
        width: 1.5rem;
        transform: translateY(-1px);
        height: 1px;
        background: #ffffff;
      }
    }
    }
  }
  .header-top {
    width: 7.2rem;
    height: 0.9rem;
    z-index: 999999;
    position: fixed;
    top: 0;
    left: 0;
    line-height: 0.9rem;
    display: flex;
    align-items: center;
    box-shadow: none;
    .header_left {
      width: 15%;
      color: #ffffff;
      font-size: 0.35rem;
      display: flex;
      align-items: center;
    }
    .center_title {
      width: 70%;
      text-align: center;
      font-size: 0.3456rem;
      color: #ffffff;
      font-weight: bold;
    }
    .header_right {
      width: 15%;
      img {
        margin: 0 auto;
        display: block;
        width: 0.6111rem;
        height: 0.6111rem;
      }
    }
  }
  .header-top.active {
    background: #ff3154;
  }
  .fixed-box {
    width: 100%;
    height: 0.9rem;
  }
  .tap-content {
    width: 100%;
    overflow-x: scroll;
    overflow-y: hidden;
    -webkit-backface-visibility: hidden;
    -webkit-perspective: 1000;
    -webkit-overflow-scrolling: touch;
    text-align: justify;
    box-sizing: border-box;
    display: flex;
    color: #ffffff;
    // margin-top: .2rem;
    // border-top: 1px solid #ededf1;
    // border-bottom: 1px solid #ededf1;
    &::-webkit-scrollbar {
      display: none;
    }
    .tap {
      text-align: center;
      flex-shrink: 0;
      width: 30%;
      font-size: 0.3rem;
      height: 0.8rem;
      line-height: 0.8rem;
      position: relative;
      // color: #979899;
    }
    .tap.active::before {
      content: "";
      display: block;
      position: absolute;
      width: 0.6rem;
      height: 0.04rem;
      background: #ffffff;
      left: 50%;
      bottom: 0;
      transform: translateX(-50%);
    }
  }
  .select-action {
    height: 0.8rem;
    .select-menu {
      position: fixed;
      top: 0.8rem;
      left: 0;
      width: 100%;
      z-index: 9;
    }
  }
}
</style>
<style lang="scss">
.page-mobile-discount {
}
</style>
